//
//  WEXStatusViewModel.swift
//  microBlog
//
//  Created by apple on 16/4/20.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
import YYText


class WEXStatusViewModel: NSObject {

    var status: WEXStatusModel? {
        
        didSet{
            
            dealMemberImage()
            
            dealContentText()
            
            dealSourceText()
            
            retweetPicSize = calcuPictureSize(status?.retweeted_status?.pic_urls)
            
            originalPicSize = calcuPictureSize(status?.pic_urls)
         
            
            creatDate = sinaDate(status?.created_at)
            
            originalAttributedString = self.attributeText(status?.text ?? "")
            
            
//            print(status?.created_at)
        }
    }
    
    // MARK: - 属性
    // 会员图标
    var memberImage: UIImage?
    // 内容
    var contentText: String?
    // 来源
    var sourceText: String?

//    var sendTime: String?
    // 转发微博配图尺寸
    var retweetPicSize: CGSize = CGSizeZero
    
    // 原创微博配图尺寸
    var originalPicSize: CGSize = CGSizeZero
    
    // 距离创建的时间
    var creatAtText: String? {
//        保证每次刷新cell都会重新计算
        return dealCreatAtText(creatDate ?? NSDate())
    }
    
    // 创建时间
    private var creatDate: NSDate?
    
    // 原创微博的内容的富文本
    var originalAttributedString: NSAttributedString?
    
    // 转发微博的内容的富文本
    var retweetAttributedString: NSAttributedString?
    
    // MARK: - 处理属性方法
    func attributeText(text: String) -> NSAttributedString {
        
//        获取原生富文本
        let attributeString = NSMutableAttributedString(string: text)
        
        var results = [WEXMatchResult]()
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            
            let result = WEXMatchResult(captureString: captureString.memory!, range: captureRange.memory)
            
            results.append(result)
        }
        
//        防止数组越界，倒着遍历
        for value in results.reverse() {
            
            if let emoticon = WEXEmoticonKeyBoardViewModel.sharedViewModel.emotionWithChs(value.captureString as String){
                
                let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")",inBundle: WEXEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle,compatibleWithTraitCollection: nil )
//                初始化一个自定义的附件
//                let attachment = WEXTextAttachment()
                
                
//                attachment.image = image
                
                let font = UIFont.systemFontOfSize(contentFont)
                
                let attr = NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: UIViewContentMode.ScaleAspectFill, attachmentSize: CGSize(width: font.lineHeight, height: font.lineHeight), alignToFont: font, alignment: YYTextVerticalAlignment.Center)
                
//                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
                
//                let attr = NSAttributedString(attachment: attachment)
                
                attributeString.replaceCharactersInRange(value.range, withAttributedString: attr)
            }
            
        }
//        添加富文本属性
        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, attributeString.length))
        attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(contentFont), range: NSMakeRange(0, attributeString.length))
        
        
        // 话题
        addColor("#[^#]+#", attribute: attributeString)
        // @
        addColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attribute: attributeString)
        // url
        addColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attribute: attributeString)
        
        return attributeString
    }
    
    //    添加特殊字符颜色
    private func addColor(regex: String, attribute: NSMutableAttributedString) {
        
        (attribute.string as NSString).enumerateStringsMatchedByRegex(regex) { (_, captureString, captureRange, _) -> Void in
            
            attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), range: captureRange.memory)
            
//            初始化一个背景对象
            let border = YYTextBorder(fillColor: UIColor(red: 177/255, green: 215/255, blue: 255/255, alpha: 1), cornerRadius: 3)
            
            border.insets = UIEdgeInsetsZero
            
//            初始化一个高亮对象
            let highlight = YYTextHighlight()
            
            highlight.setColor(UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1))
//            设置高亮状态下的背景
            highlight.setBackgroundBorder(border)
            
            let s = (captureString.memory)! as String
            
            highlight.tapAction = { (containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect)->() in
                    SVProgressHUD.showInfoWithStatus(s)
                
            }
            
            attribute.yy_setTextHighlight(highlight, range: captureRange.memory)
            
        }
        
    }
    
    //    处理时间格式的方法
    private func sinaDate(creatAt: String?) -> NSDate? {
        
        guard let creat_at = creatAt else{
            
            return nil
        }
//        初始化格式
        let fm = NSDateFormatter()
        
        fm.locale = NSLocale(localeIdentifier: "en")
        // 指定格式字符串   Sun Nov 22 11:25:56 +0800 2015
        fm.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        // 注意，此处是从字符串中获取日期
        let creatDate = fm.dateFromString(creat_at)
        
        return creatDate
        
    }
    
    //    处理创建时间的方法
    private func dealCreatAtText(creatDate: NSDate) -> String{
        
//        创建时间格式
        let fm = NSDateFormatter()
        
        fm.locale = NSLocale(localeIdentifier: "en")
//        实例化日历对象
        let calendar = NSCalendar.currentCalendar()
        
//        判断是否是今年
        if isDateInThisYear(creatDate) {
//            判断是否是今天
            if calendar.isDateInToday(creatDate) {
//                获取当前时间
                let currentDate = NSDate()
//                print(currentDate)
                
                var timeInterval = Int(currentDate.timeIntervalSinceDate(creatDate))
                
//                print(timeInterval)
                
                if timeInterval < 60 {
                    return "刚刚"
                }else if timeInterval < 3600 {
                    
                    timeInterval = timeInterval / 60
                    
                    return "\(timeInterval)分钟前"
                }else{
                    
                    timeInterval = timeInterval / 3600
                    
                    return "\(timeInterval)小时前"
                }
            }else if calendar.isDateInYesterday(creatDate) {
                
//                昨天 几点：几分
                fm.dateFormat = "昨天 hh:mm"
                
                return fm.stringFromDate(creatDate)
                
            }else {
                
//                几月-几日 几点：几分
                fm.dateFormat = "MM-dd hh:mm"
                
                return fm.stringFromDate(creatDate)
                
            }
        }else {
//            哪年—哪月-哪日 几点：几分
            fm.dateFormat = "yyyy-MM-dd hh:mm"
            
            return fm.stringFromDate(creatDate)
        }
        
        
        
        
    }
    
    private func isDateInThisYear(targetDate: NSDate) -> Bool{
        
//        获取当前的时间
        let currentDate = NSDate()
        
        let fm = NSDateFormatter()
//        获取年份的格式
        fm.dateFormat = "yyyy"
        
        let targetYear = fm.stringFromDate(targetDate)
        let currentYear = fm.stringFromDate(currentDate)
        
        return targetYear == currentYear
        
        
    }
    
    //    更新单张配图尺寸
    func updateSinglePicSize() {
        
        retweetPicSize = calcuSinglePicSize(status?.retweeted_status?.pic_urls)
        originalPicSize = calcuSinglePicSize(status?.pic_urls)
        
    }
    
    //    处理单张配图的尺寸
    private func calcuSinglePicSize(pic_urls: [WEXPicInfoModel]?) -> CGSize {
        
        guard let urlString = pic_urls?.first?.thumbnail_pic else{
            
            return CGSizeZero
        }
        
        if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString) {
            
            let scale = UIScreen.mainScreen().scale
            

            var size = CGSize(width: image.size.width * scale , height: image.size.height * scale)
            
            if  size.width < 50 {
                
                let height = size.height * 50 / size.width
                
                size.width = 50
                
                size.height = height > 120 ? 120 : height
                
            }
            if size.width > 300 {
                
                let height = size.height / size.width * 300
                
                size.width = 300
                
                size.height = height > 400 ? 400 : height
            }
            
            return size
        }
        return CGSizeZero
        
    }
    //    处理配图尺寸方法
    private func calcuPictureSize(pic_urls: [WEXPicInfoModel]? ) -> CGSize {
        
        let count = pic_urls?.count ?? 0
        
        if count == 0 {
            
            return CGSizeZero
        }
        
//        计算列数
        let col = count == 4 ? 2 : (count > 3 ? 3 : count)
        
//        计算行数
        let row = (count - 1) / 3 + 1
        
        let itemMargin: CGFloat = 5
        
//        计算item的宽高
        let itemWH = (SCREENWIDTH - 2 * commonMargin - 2 * itemMargin) / 3
        
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin

        
        return CGSizeMake(width, height)
        
        
    }
    
    //    处理数据的方法
    private func dealMemberImage() {
        
    if let rank = status?.user?.mbrank where (rank > 0 && rank < 7) {
        
//        print(rank)
        
        memberImage = UIImage(named: "common_icon_membership_level\(rank)")
    }
    
    
    }

    //    处理正文内容
    private func dealContentText() {
        
        if let text = status?.retweeted_status {
            
            if let name = text.user?.name, content = text.text {
                
                contentText = "@\(name): \(content)"
                
                retweetAttributedString = self.attributeText(contentText!)
            }
            
        }
        
    }

    //    处理来源
    private func dealSourceText() {
        
        // <a href=\"http://app.weibo.com/t/feed/5B6hUc\" rel=\"nofollow\">iPhone 6s Plus</a>
        
        guard let text = status?.source else{
            
            return
        }
        
        if let startIndex = text.rangeOfString("\">")?.endIndex, endIndex = text.rangeOfString("</")?.startIndex{
            
            let result = text.substringWithRange(startIndex..<endIndex)
            
            sourceText = "来自 \(result)"
            
            
        }
        
        
    }
}
